package com.ruoyi.api.zhifubao.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author 寻觅
 * @since 2025-06-17
 * 支付宝沙盒环境退款接口实现
 */
@Component
public class AlipayRefundDemo {

    /**
     * 应用私钥（从配置文件注入，需包含完整RSA格式）
     * 示例配置：alipay.appPrivateKey=-----BEGIN PRIVATE KEY-----\nMIIEvgIBADAN...\n-----END PRIVATE KEY-----
     */
    @Value("${alipay.appPrivateKey}")
    private String merchantPrivateKey;

    /**
     * 支付宝公钥（从配置文件注入）
     * 示例配置：alipay.alipayPublicKey=-----BEGIN PUBLIC KEY-----\nMIIBIjAN...\n-----END PUBLIC KEY-----
     */
    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    // 沙盒环境网关（固定值，无需修改）
    private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    // 沙盒应用ID（需替换为你的沙盒应用ID）
    private static final String APP_ID = "9021000132691049";
    // 签名类型
    private static final String SIGN_TYPE = "RSA2";
    // 字符集
    private static final String CHARSET = "UTF-8";
    // 数据格式
    private static final String FORMAT = "json";

    /**
     * 传统SDK退款接口调用（推荐使用此方式）
     */
    public void refundByTraditionalSdk() {
        try {
            // 校验私钥是否正确注入
            if (merchantPrivateKey == null || merchantPrivateKey.contains("appPrivateKey:")) {
                throw new IllegalArgumentException("商户私钥未正确注入或格式错误，请检查application.yml配置");
            }

            // 创建AlipayClient实例（使用注入的私钥和公钥）
            AlipayClient alipayClient = new DefaultAlipayClient(
                    GATEWAY_URL,
                    APP_ID,
                    merchantPrivateKey,
                    FORMAT,
                    CHARSET,
                    alipayPublicKey,
                    SIGN_TYPE
            );

            // 构造退款请求参数
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\"2021010122001415360539260374\"," +
                    "\"trade_no\":\"2021010122001415360539260374\"," +
                    "\"refund_amount\":10.00," +
                    "\"refund_reason\":\"测试退款\"," +
                    "\"out_request_no\":\"HZ01RF001\"" +
                    "}");

            // 执行退款请求
            AlipayTradeRefundResponse response = alipayClient.execute(request);

            // 处理响应结果
            if (response.isSuccess()) {
                System.out.println("退款成功！");
                System.out.println("交易号：" + response.getTradeNo());
                System.out.println("商户订单号：" + response.getOutTradeNo());
                System.out.println("退款金额：" + response.getRefundFee());
            } else {
                System.out.println("退款失败！");
                System.out.println("错误码：" + response.getCode());
                System.out.println("错误信息：" + response.getMsg());
            }
        } catch (AlipayApiException e) {
            System.err.println("退款接口调用异常，原因：" + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 测试入口（仅用于本地测试，生产环境建议通过Spring Bean调用）
     */
    public static void main(String[] args) {
        AlipayRefundDemo demo = new AlipayRefundDemo();
        demo.refundByTraditionalSdk();
        // demo.refundByEasySdk(); // 如需测试EasySDK，取消此行注释
    }
}
